﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic ;
using System.Data.SqlClient;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors.Repository;

namespace APPLICATION.UserManager
{
    public partial class FrmPages : Form
    {
        public FrmPages()
        {
            InitializeComponent();
            this.SelectedIDChanged += new SelectedIDDelegate(FrmPages_SelectedIDChanged);
        }        

        private  delegate void SelectedIDDelegate(string ID);
        private event  SelectedIDDelegate SelectedIDChanged;


        private string _SelectedID;
        public string SelectedID
        {
            get
            {
                return _SelectedID;
            }
            set
            {
                _SelectedID = value;
                if (SelectedIDChanged != null)
                {
                    SelectedIDChanged(value);
                }
            }
        }        

        public string SelectedCategoryValue;
        private string codeOP;
        private DataTable dt ;

        public bool myMessageAndOperation()
        {
            if (this.isEdited())
            {
                DialogResult dr1 = new DialogResult();
                dr1 = MessageBox.Show(this, "Do you want to save the changes?", "User Manager", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                switch (dr1)
                {
                    case DialogResult.Yes:
                        return this.save();
                    case DialogResult.No:
                        dt.RejectChanges();
                        return true;
                    case DialogResult.Cancel:
                        return false;
                }
            }
            return true;            
        }

        public bool isEdited()
        {            
            if (dt == null)
            {
                return false;
            }
            gridViewAction.CloseEditor();
            gridViewAction.UpdateCurrentRow();
            
            bindingSource1.EndEdit();            
            DataView filteredDw = new DataView(dt);
            filteredDw.RowStateFilter = DataViewRowState.ModifiedOriginal;
            return Convert.ToBoolean(filteredDw.Count);
        }

        private void fillXML()
        {
            DataView sourceDw = new DataView(dt);
            sourceDw.RowStateFilter = DataViewRowState.ModifiedOriginal;
            GlobalDataFile.UserManagerDataSet.Attach.Clear();
            foreach (DataRow dr in sourceDw.ToTable().Rows)
            {
                bool isGrant = true;
                if (Convert.ToBoolean(dr["isGrant"]))
                { isGrant = false; }
                GlobalDataFile.UserManagerDataSet.Attach.Rows.Add(Convert.ToInt32(SelectedID), isGrant, dr[0], codeOP);
            }
            GlobalDataFile.UserManagerDataSet.Attach.AcceptChanges();
        }

        private bool save()
        {
            
            UMdataAccess DataAccess = new UMdataAccess();
            System.IO.MemoryStream s = new System.IO.MemoryStream();
            //fill Attach datatable
            this.fillXML();
            GlobalDataFile.UserManagerDataSet.Attach.WriteXml(s, true);

            s.Seek(0, System.IO.SeekOrigin.Begin);

            System.IO.StreamReader sr = new System.IO.StreamReader(s);

            string xmlString;
            xmlString = sr.ReadToEnd();
            //close             
            sr.Close();
            sr.Dispose();

            SqlParameter sqlPar = new SqlParameter("@docXML", SqlDbType.Xml);
            sqlPar.Value = xmlString;
            if (DataAccess.tx_UMSRGrantURA(sqlPar))
            {
                dt.AcceptChanges();
                buttonSave.Enabled = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        private void FillSelectedPage()
        {
            UMdataAccess DataAccess = new UMdataAccess();
            if (string.IsNullOrEmpty(this._SelectedID))
            {
                GlobalDataFile.UsersInPerAction.Clear();
                GlobalDataFile.UsersInPerRole.Clear();
                GlobalDataFile.RolesInPerUser.Clear();
                GlobalDataFile.RolesInPerAction.Clear();
                GlobalDataFile.ActionsInPerUser.Clear();
                GlobalDataFile.ActionsInPerRole.Clear();
                return;
            }
            
            if (tabControl1.SelectedTabPage.Name == "xtraTabPageAction")
            {
                if (SelectedCategoryValue == "Users")
                {
                    codeOP = "13";
                    DataAccess.FillActionsInPerUser(SelectedID);
                    dt =  GlobalDataFile.ActionsInPerUser;
                    bindingSource1.DataSource = dt;
                    gridControlAction.DataSource = bindingSource1;//UserManagerDataSet.fn_TGetActions1;                    
                }
                else if (SelectedCategoryValue == "Roles")
                {
                    codeOP = "23";
                    DataAccess.FillActionsInPerRole(SelectedID);
                    dt = GlobalDataFile.ActionsInPerRole;
                    bindingSource1.DataSource = dt;
                    gridControlAction.DataSource = bindingSource1;
                }
            }
            else if (tabControl1.SelectedTabPage.Name == "xtraTabPageRole")
            {                
                if (SelectedCategoryValue == "Users")
                {
                    codeOP = "12";
                    DataAccess.FillRolesInPerUser(SelectedID);
                    dt = GlobalDataFile.RolesInPerUser;
                    bindingSource1.DataSource = dt;
                    gridControlRole.DataSource = bindingSource1;
                }
                else if (SelectedCategoryValue == "Actions")
                {
                    codeOP = "32";
                    DataAccess.FillRolesInPerAction(SelectedID);
                    dt = GlobalDataFile.RolesInPerAction;
                    bindingSource1.DataSource = dt;
                    gridControlRole.DataSource =bindingSource1;
                }
            }
            else if (tabControl1.SelectedTabPage.Name == "xtraTabPageUser")
            {
                if (SelectedCategoryValue == "Roles")
                {
                    codeOP = "21";
                    DataAccess.FillUsersInPerRole(SelectedID);
                    dt = GlobalDataFile.UsersInPerRole;
                    bindingSource1.DataSource = dt;
                    gridControlUser.DataSource = bindingSource1;
                }
                else if (SelectedCategoryValue == "Actions")
                {
                    codeOP = "31";
                    DataAccess.FillUsersInPerAction(SelectedID);
                    dt = GlobalDataFile.UsersInPerAction;
                    bindingSource1.DataSource = dt;
                    gridControlUser.DataSource = bindingSource1;
                }
            }
        }

        public void VisibleTabs(string SelectedCategoryText)
        {
            //
            DevExpress.XtraGrid.Columns.GridColumn a = new DevExpress.XtraGrid.Columns.GridColumn();
            SelectedCategoryValue = SelectedCategoryText;
            foreach (DevExpress.XtraTab.XtraTabPage Tab in tabControl1.TabPages)
            {
                if (Tab.Tag.ToString().IndexOf("," + SelectedCategoryText) > -1)
                {
                    Tab.PageVisible = true;
                }
                else
                {
                    Tab.PageVisible = false;
                }
            }
        }

        private void FrmPages_SelectedIDChanged(string ID)
        {
            this.FillSelectedPage();
        }

        private void tabControl1_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            if (this.isEdited())
            {
                if (this.myMessageAndOperation() == false)
                {
                    e.Cancel = true;
                }
            }
        }

        private void tabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
           
            this.FillSelectedPage();
        }

        private void FrmPages_Load(object sender, EventArgs e)
        {
            gridViewAction.Columns[1].BestFit();
            gridViewRole.OptionsView.ColumnAutoWidth = true;
            gridViewRole.Columns[1].BestFit();
            for (int i = 0; i < gridViewUser.Columns.Count-2; i++)
            {
            	gridViewUser.Columns[i].BestFit();
            }            
        }

        void bindingSource1_CurrentItemChanged(object sender, EventArgs e)
        {
            buttonSave.Enabled = true;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (isEdited())
            {
                save();
            }
        }

        private void gridViewAction_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            buttonSave.Enabled = true;
        }
    }
}
